<template>
    <view class="content">
        <van-popup position="bottom" @click-overlay="closePopup" :show="showSpecsPopup" round
            custom-style="width: 100%;background:#ffffff;overflow: hidden; height:70%">
            <view class="popup-content">

                <view class="popup-main">
                    <view style="display: flex; justify-content: space-between;">
                        <!-- 商品内容 -->
                        <view class="goodsDetail">
                            <view class="goodsPic"> <img class="img" :src="imageUrl ? imageUrl : ebStoreProduct.image" alt=""> </view>
                            <view class="goodsText">
                                <view class="goods_price">
                                    <view class="goods_price_num r13">¥{{ price }}</view>
                                    <view class="goods_price_text r8">最多可用</view>
                                    <view class="goods_price_num"> <img
                                            src="https://17lelife-bucket.oss-cn-beijing.aliyuncs.com/WeChat-App-Picture/shangcheng/jinbi.png"
                                            alt="" style="height: 14px; width: 14px; margin-right: 7px;" /> {{ score }}
                                    </view>
                                </view>
                                <view class="goods_T">{{ ebStoreProduct.storeName }} {{ selectedSuk }}</view>
                            </view>
                        </view>
                        <!-- 关闭弹窗按钮 -->
                        <view>
                            <van-icon name="cross" color="#FFFFFF" size="15" @click="closePopup" />
                        </view>
                    </view>
                    <scroll-view class="scroll-content " scroll-y :lower-threshold="120" show-scrollbar="false"  :refresher-enabled="false" >
                        <!-- 规格   口味 -->
                        <view class="specs-box taste" v-for="(item, index) in ebProductAttr" :key="index" :id="item.id">
                            <view class="specs-box-title">{{ item.attrName }}</view>
                            <view class="specs-box-select">
                                <view class="popup-sort">
                                    <!-- :class="{ cur_border: (isSelected(item.id,single) ) , dis_border: single.disabled , 'dis_border':(single.disabled || single.outOfStock)}" -->
                                    <view
                                        class="popup-item inStock"
                                        :class="{ cur_border: (isSelected(item.id,single) ) , dis_border: single.disabled , 'out-of-stock':( single.outOfStock)}"
                                         v-for="(single, ind) in item.ebProductAttrSecond" :key="ind" :id="single.id"
                                        @click="selectSpec(item.id,item.attrName,single)">
                                        {{ single.attrName }}
                                        <!-- <span v-if="single.outOfStock" class="out-of-stock-tag">缺货</span> -->
                                    </view>
                                </view>
                            </view>
                        </view>
                        <!-- 数量 -->
                        <view class="specs-box number">
                            <view class="specs-box-title">数量 <span class="specs-box-title-span"
                                    v-if="ebStoreProduct.quotaNum && ebStoreProduct.quotaNum > 0">（限购{{ ebStoreProduct.quotaNum }}{{ ebStoreProduct.unitName }}）</span>
                            </view>
                            <view class="specs-box-select">
                                <van-stepper :value="buyNum" :max="ebStoreProduct.quotaNum" :min="ebStoreProduct.minbuynum ?ebStoreProduct.minbuynum :1" integer @change="handleStepperChange"/>
                            </view>
                        </view>

                        <van-toast id="van-toast" />
                    </scroll-view>

                </view>
                <!-- <view class="goodsAction nav_box" v-if="parentSign==='detail'">
                    <van-goods-action class="my-goods-action" v-if="buttonStatus === 0">
                        <van-goods-action-button
                            class="my-action-buttonL"
                            plain
                            color="#111111"
                            text="加入购物车"
                            @click="addToCart" />
                        <van-goods-action-button color="#FF6203" text="立即购买" @click="onClickBuy" />
                    </van-goods-action>
                    <van-goods-action v-else>
                        <van-goods-action-button v-if="buttonStatus === 1" color="#FF6203" text="加入购物车" @click="addToCart" />
                        <van-goods-action-button v-if="buttonStatus===2 && biaozhi!=='find'" color="#FF6203" text="立即购买" @click="onClickBuy" />
                        <van-goods-action-button v-if="buttonStatus===2 && biaozhi==='find'" color="#FF6203" text="立即拼团" @click="onClickGroupBuy" />
                    </van-goods-action>
                </view> -->
                <view class="bottom " v-if="parentSign === 'cart'">
                    <!-- <van-goods-action class="my-goods-action" id="my-goods-action">
                        <van-goods-action-button color="#FF6203" text="确定" @click="onClickBuy" />
                    </van-goods-action> -->
                    <van-button type="primary" class="" @click="onClickBuy">确定</van-button>
                </view>
                <view class="bottom" v-if="parentSign ==='groupBuy'">
                    <van-button type="primary" class="" @click="onClickGroupBuy">立即拼团</van-button>
                </view>
            </view>
        </van-popup>
    </view>
</template>
<script>
import Toast from '@/wxcomponents/vant/toast/toast'

import { addToShoppingCartApi,multiSpecAndNumModifyApi } from '@/api/shoppingCart'

export default {
    props: {
        showSpecsPopup: {
            type: Boolean,
            default: () => false
        },
        roleName: {
            type: String,
            default:  ''
        },
        buttonStatus: {
            type: Number,
            default: 0
        },
        parentSign: {
            type: String,
            default:''
        },
        biaozhi: {
            type: String,
            default:''
        },
      
        ebStoreProduct: {
            type: Object,
            default: () => { }
        },
        ebProductAttr: {
            type: Array,
            default: () => []
        },
        ebStoreProductAttrValue: {
            type: Array,
            default: () => []
        },
        ebStoreProductAttrRelationDTO: {
            type: Array,
            default: () => []
        },
        selectSuk: {
            type: String,
            default: ''
        },
        cartProInfo: {
            type: Object,
            default: () => {}
        }

    },
    data() {
        return {
            curSpecsOuterIndex: -1,
            curSpecsInnerIndex: -1,
            curWeight: -1,

            date: '',
            show: true,
            title: 'Hello',
            option: {},
            url: '',
            buyNum: 1, //数量选择   接口传参
            
            price: '160',
            score: '160',
            imageUrl: '', //规格对应的图片
            curObj: [],
            specsArray: [],
            newSpecsList: [],
            productId: undefined,
            productAttrValueId: undefined,
            chooseSize: '',
            chooseColor: '',

            selectedSpecs: {},// 存放规格名称  pid:attrName
            selectedSpecsIds:{},  // 存放规格id pid:id
            // 初始化时将所有规格选项设为可用
            initialized: false,
            selectedSukPids:[], //选中的规格的pid
            selectedSukIds:[], //选中的规格id
            selectedSukValues:[],  //选中的规格atrrName
            selectedSuk:'',  //选中的规格字符串  页面显示的
            stockInitialized: false,
            // ebProductAttr: [
            //     { 
            //         id: 121,
            //         pid: 0,
            //         attrName: '颜色',
            //         ebProductAttrSecond: [
            //             {
            //                 "id": 125,
            //                 "pid": 121,
            //                 "attrName": "格物致知蓝咖"
            //             },
            //             {
            //                 "id": 124,
            //                 "pid": 121,
            //                 "attrName": "格物致知红色"
            //             }
            //         ]
            //     },
            //     // {
            //     //     id : 141,
            //     //     pid: 0,
            //     //     "attrName": "状态",
            //     //     "ebProductAttrSecond":[
            //     //         {
            //     //             "id":130,
            //     //             "pid":141,
            //     //             "attrName":"预售"
            //     //         },
            //     //         {
            //     //             "id":131,
            //     //             "pid":141,
            //     //             "attrName":"现货"
            //     //         }
            //     //     ]
            //     // },
            //     {
            //         id : 126,
            //         pid: 0,
            //         "attrName": "尺码",
            //         "ebProductAttrSecond":[
            //             {
            //                 "id":127,
            //                 "pid":126,
            //                 "attrName":"200 * 27cm"
            //             },
            //             {
            //                 "id":128,
            //                 "pid":126,
            //                 "attrName":"240 * 30cm"
            //             }
            //         ]
            //     }
            // ],
            // ebStoreProductAttrValue: [
            //     {
            //         "id": 21,
            //         "productId": 3,
            //         "suk": "格物致知红色,200 * 27cm",
            //         "stock": 10,
            //         "sales": 0,
            //         "price": 374.00,
            //         "integral": 0.00,
            //         "image": "crmebimage/public/maintain/2021/12/25/5486775d8cad4fd8adfc254d2e93857cn0wu5hq8f4.jpg",
            //         "unique": null,
            //         "cost": 100.00,
            //         "barCode": "",
            //         "otPrice": 412.00,
            //         "weight": 0.50,
            //         "volume": 0.00,
            //         "brokerage": 0.00,
            //         "brokerageTwo": 0.00,
            //         "type": 0,
            //         "quota": 0,
            //         "quotaShow": 0,
            //         "isDel": false,
            //         "attrValue": null
            //     }, {
            //         "id": 22,
            //         "productId": 3,
            //         "suk": "格物致知红色,240 * 30cm",
            //         "stock": 677,
            //         "sales": 1,
            //         "price": 374.00,
            //         "integral": 0.00,
            //         "image": "crmebimage/public/maintain/2021/12/25/5486775d8cad4fd8adfc254d2e93857cn0wu5hq8f4.jpg",
            //         "unique": null,
            //         "cost": 100.00,
            //         "barCode": "",
            //         "otPrice": 412.00,
            //         "weight": 0.50,
            //         "volume": 0.00,
            //         "brokerage": 0.00,
            //         "brokerageTwo": 0.00,
            //         "type": 0,
            //         "quota": 0,
            //         "quotaShow": 0,
            //         "isDel": false,
            //         "attrValue": null
            //     }, {
            //         "id": 19,
            //         "productId": 3,
            //         "suk": "格物致知蓝咖,200 * 27cm",
            //         "stock": 0,
            //         "sales": 0,
            //         "price": 374.00,
            //         "integral": 30.00,
            //         "image": "crmebimage/public/maintain/2021/12/25/5486775d8cad4fd8adfc254d2e93857cn0wu5hq8f4.jpg",
            //         "unique": null,
            //         "cost": 100.00,
            //         "barCode": "",
            //         "otPrice": 412.00,
            //         "weight": 0.50,
            //         "volume": 0.00,
            //         "brokerage": 0.00,
            //         "brokerageTwo": 0.00,
            //         "type": 0,
            //         "quota": 0,
            //         "quotaShow": 0,
            //         "isDel": false,
            //         "attrValue": null
            //     }, {
            //         "id": 20,
            //         "productId": 3,
            //         "suk": "格物致知蓝咖,240 * 30cm",
            //         "stock": 366,
            //         "sales": 0,
            //         "price": 374.00,
            //         "integral": 10.00,
            //         "image": "crmebimage/public/maintain/2021/12/25/5486775d8cad4fd8adfc254d2e93857cn0wu5hq8f4.jpg",
            //         "unique": null,
            //         "cost": 100.00,
            //         "barCode": "",
            //         "otPrice": 412.00,
            //         "weight": 0.50,
            //         "volume": 0.00,
            //         "brokerage": 0.00,
            //         "brokerageTwo": 0.00,
            //         "type": 0,
            //         "quota": 0,
            //         "quotaShow": 0,
            //         "isDel": false,
            //         "attrValue": null
            //     }
            // ],

            // ebStoreProductAttrRelationDTO: [
            //     {
            //         "productId": 3,
            //         "valueId": 19,
            //         "specId": 125,
            //         "specName": "格物致知蓝咖",
            //         "specParentId": 121,
            //         "specParentName": "颜色"
            //     },
            //     {
            //         "productId": 3,
            //         "valueId": 19,
            //         "specId": 127,
            //         "specName": "200 * 27cm",
            //         "specParentId": 126,
            //         "specParentName": "尺码"
            //     },
            //     {
            //         "productId": 3,
            //         "valueId": 20,
            //         "specId": 125,
            //         "specName": "格物致知蓝咖",
            //         "specParentId": 121,
            //         "specParentName": "颜色"
            //     },
            //     {
            //         "productId": 3,
            //         "valueId": 20,
            //         "specId": 128,
            //         "specName": "240 * 30cm",
            //         "specParentId": 126,
            //         "specParentName": "尺码"
            //     },
            //     {
            //         "productId": 3,
            //         "valueId": 21,
            //         "specId": 124,
            //         "specName": "格物致知红色",
            //         "specParentId": 121,
            //         "specParentName": "颜色"
            //     },
            //     {
            //         "productId": 3,
            //         "valueId": 21,
            //         "specId": 127,
            //         "specName": "200 * 27cm",
            //         "specParentId": 126,
            //         "specParentName": "尺码"
            //     },
            //     {
            //         "productId": 3,
            //         "valueId": 22,
            //         "specId": 124,
            //         "specName": "格物致知红色",
            //         "specParentId": 121,
            //         "specParentName": "颜色"
            //     },
            //     {
            //         "productId": 3,
            //         "valueId": 22,
            //         "specId": 128,
            //         "specName": "240 * 30cm",
            //         "specParentId": 126,
            //         "specParentName": "尺码"
            //     }
            // ],
            // selectSuk:'格物致知蓝咖,240 * 30cm'
            selectedAttrValue:null,
            cartId:null,
        }
    },
    watch: {
        ebStoreProduct: {
            immediate: true, // 这句重要
            handler (newVal) {
                // console.log('newVal' + newval, '子组件watch')
                // if (this.ebStoreProduct && this.ebStoreProduct.hasOwnProperty('id')) {
                //     this.productId=this.ebStoreProduct.id
                // }
                // if (this.ebStoreProduct && this.ebStoreProduct.hasOwnProperty('price')) {
                //     this.price = this.ebStoreProduct.price || '0';
                // }
                // if (this.ebStoreProduct && this.ebStoreProduct.hasOwnProperty('integral')) {
                //     this.score = this.ebStoreProduct.integral || '0';
                // }
                // 添加空值校验
                if (newVal && Object.keys(newVal).length > 0) {
                    console.log('收到有效商品数据', newVal);
                    this.$nextTick(() => {
                        this.productId = newVal.id;
                        this.price = newVal.price || '0';
                        this.score = newVal.integral || '0';
                        this.imageUrl = newVal.image || undefined
                        // 当数据到达后重新初始化规格
                        if (this.selectSuk && this.ebProductAttr.length > 0) {
                            this.setSpecsBySuk(this.selectSuk);
                        }
                    });
                }
            },
            deep: true
        },
        selectSuk:{
            immediate: true, // 这句重要
            handler (newVal) {
                console.log(newVal,this.selectSuk,'pppp',this.ebProductAttr.length,'length')
                if (newVal && this.ebProductAttr.length > 0) {
                    this.setSpecsBySuk(newVal);
                }
            },
            deep: true
        },
        cartProInfo: {
            immediate: true, // 这句重要
            handler (newVal) {
                // 添加空值保护
                const safeData = newVal || {};
                console.log(safeData, 'cartProInfo');
                this.cartId = safeData.id || null;
                this.buyNum = safeData.cartNum || 1;
                console.log(this.buyNum,'this.buyNum')
            },
        },
        showSpecsPopup(newVal) {
            if (newVal && this.selectSuk) {
                this.$nextTick(() => {
                    this.setSpecsBySuk(this.selectSuk);
                    this.initStockStatus(); // 弹窗打开时强制初始化  要选中购物车中选择的规格 所以不初始化
                });
            }
        },
        
        // showSpecsPopup(newVal, oldVal) {
        //     console.log(newVal,oldVal)
        //     if (newVal && !oldVal) {
        //         // 当弹窗从关闭状态变为打开状态时，清空选中规格的数据
        //         this.clearData();
        //         if (this.selectSuk && this.ebProductAttr.length>0) {
        //             this.selectedSuk=this.selectSuk
        //             this.$nextTick(() => {
        //                 this.setSpecsBySuk(this.selectSuk);
        //             })
        //         }
        //     }
        // }
    },
    computed: {
        // sortedArr() {
        //     return this.curObj.slice().sort((a, b) => a.specCategoryIndex - b.specCategoryIndex);
        // }
    },
    onLoad(data) {
        console.log(this.ebStoreProduct,'this.ebStoreProduct')
        this.price = this.ebStoreProduct.price || '0'
        this.score = this.ebStoreProduct.integral || '0'
        this.productId = this.ebStoreProduct.id
        // this.selectSuk= this.ebStoreProduct.productAttrValueName
        console.log(this.selectSuk,'selectSuk',this.ebProductAttr.length,'this.ebProductAttr')
        if (this.selectSuk) {
            this.selectedSuk=this.selectSuk
            this.setSpecsBySuk(this.selectSuk)
        }
    },
    onReady() {
        
        // 创建一个空对象用于存储整合后的数据
        const integratedData = {};

        // 遍历ebStoreProductAttrValue数组，以id为键存储对象
        this.ebStoreProductAttrValue.forEach(item => {
            integratedData[item.id] = { ...item, relations: [] };
        });

        // 遍历ebStoreProductAttrRelationDTO数组，合并关系数据
        this.ebStoreProductAttrRelationDTO.forEach(relation => {
            const valueId = relation.valueId;
            if (integratedData[valueId]) {
                integratedData[valueId].relations.push(relation);
            }
        });

        // 将整合后的对象转换为数组
        const resultArray = Object.values(integratedData);
        console.log(integratedData,'integratedData',resultArray,'resultArray');
        // 初始化库存状态
        this.initStockStatus();
    },
    methods: {
        clearData(){
            // this.selectedSukPids=[] //选中的规格的pid
            // this.selectedSukIds=[]//选中的规格id
            // this.selectedSukValues=[]  //选中的规格atrrName
            this.selectedSpecs={}// 存放规格名称  pid:attrName
            this.selectedSpecsIds={}  // 存放规格id pid:id
        },
        // 修改生成selectedSuk的逻辑
        getOrderedSuk() {
            // 按照规格分类的顺序生成suk
            return this.ebProductAttr
                .map(group => this.selectedSpecs[group.id])
                .filter(Boolean)
                .join(',');
        },
        setSpecsBySuk(suk) {
            console.log(suk,'suk',this.ebProductAttr,'ebProductAttr--------')
            // const sukParts = suk;
            const sukParts = suk.split(',');
            console.log(sukParts,'oooo')
            this.clearData()
            this.ebProductAttr.forEach(specGroup => {
                console.log(sukParts,'sukParts',specGroup,'specGroup')
                specGroup.ebProductAttrSecond.forEach(spec => {
                    if (sukParts.includes(spec.attrName)) { console.log(sukParts.includes(spec.attrName),'opopop',sukParts.includes('格物致知红色'),)
                        this.selectSpec(specGroup.id, specGroup.attrName, spec);
                    }
                });
            });
            // 强制更新视图
            this.$forceUpdate();
        },
        setSpecsByIds(ids) {
            this.ebProductAttr.forEach(specGroup => {
                specGroup.ebProductAttrSecond.forEach(spec => {
                    if (ids.includes(spec.id)) {
                        this.selectSpec(specGroup.id, specGroup.attrName, spec);
                    }
                });
            });
        },
        // 页面一开始进行判断   如果含有由某一规格的stock都为0   则这个规格库存为0   显示缺货
        // initStockStatus() {
        //     if (this.stockInitialized) return;
        //     this.ebProductAttr.forEach(specGroup => {
        //         specGroup.ebProductAttrSecond.forEach(spec => {
        //             spec.outOfStock = false;
        //             spec.disabled = false;
        //             // const allStockZero = this.ebStoreProductAttrValue.every(item => {
        //             //     console.log(item.suk.includes(spec.attrName),'item.suk')
        //             //     if (item.suk.includes(spec.attrName)&&item.stock === 0) {
        //             //         return item.stock === 0;
        //             //     }
        //             //     return true;
        //             // });
        //             const filteredItems = this.ebStoreProductAttrValue.filter(item => item.suk.includes(spec.attrName));
        //             const allStockZero = filteredItems.every(item => item.stock === 0);
        //             if(allStockZero){
        //                 spec.outOfStock = true;
        //                 spec.disabled = true
        //             }
        //             console.log(allStockZero,'allStockZero')
        //         });
        //     });
        //     console.log(this.ebProductAttr,'ebProductAttr')

        //     this.stockInitialized = true;
        // },

        initStockStatus() {
            this.stockInitialized = false; // 新增重置标记
            if (this.stockInitialized) return;
            // 初始化时验证所有规格的有效性
            this.ebProductAttr.forEach(specGroup => {
                specGroup.ebProductAttrSecond.forEach(spec => {
                    // 精确匹配规格组合（新增组合存在性检查）
                    const validCombinations = this.ebStoreProductAttrValue.filter(item => {
                        // 将suk分割为数组进行精确匹配
                        const sukParts = item.suk.split(',');
                        return sukParts.some(part => part.trim() === spec.attrName);
                    });

                    // 组合存在性验证（新增）
                    const hasValidCombination = validCombinations.some(item => {
                        const otherSpecs = item.suk.split(',').filter(p => p !== spec.attrName);
                        return otherSpecs.every(other =>
                            this.ebStoreProductAttrValue.some(v =>
                                v.suk.includes(other) && v.stock > 0
                            )
                        );
                    });

                    // 库存状态判断（优化）
                    const allStockZero = validCombinations.length > 0 &&
                        validCombinations.every(item => item.stock === 0);

                    spec.outOfStock = hasValidCombination && allStockZero;  // 只有当组合存在且库存为零时才显示缺货  原有的 //!hasValidCombination || allStockZero
                    spec.disabled = !hasValidCombination;
                    if (!hasValidCombination) {
                        spec.permanentDisable = true; // 新增永久禁用标记
                    }
                });
            });
            this.stockInitialized = true;
        },
        init() {
            if (!this.initialized) {
                this.ebProductAttr.forEach(single => {
                    single.ebProductAttrSecond.forEach(every => {
                        every.disabled = false;
                        every.outOfStock=false
                    });
                });
                this.initialized = true;
            }
        },
        selectSpec(pid, parentSpecs, spec) {

            console.log(pid, parentSpecs,'parentSpecs', spec,'parentSpecs');
            // // 不能取消选中
            // // this.selectedSpecs[pid] = spec.attrName;
            // // this.selectedSpecsIds[spec.id] = spec.attrName;

            // // 点击已选商品  可以实现取消选中
            // if (this.selectedSpecs[pid] == spec.attrName) {
            //     // 如果当前点击的规格已经被选中，取消选中
            //     delete this.selectedSpecs[pid];
            //     delete this.selectedSpecsIds[pid];
            // } else {
            //     // 否则，选中该规格
            //     this.selectedSpecs[pid] = spec.attrName;
            //     this.selectedSpecsIds[pid] = spec.id;
            // }
            const newSelectedSpecs = { ...this.selectedSpecs };
            const newSelectedSpecsIds = { ...this.selectedSpecsIds };

            if (newSelectedSpecs[pid] === spec.attrName) {
                delete newSelectedSpecs[pid];
                delete newSelectedSpecsIds[pid];
            } else {
                // 清空同组已选规格
                Object.keys(newSelectedSpecs).forEach(key => {
                    if (this.ebProductAttr.some(g => g.id === Number(key) && g.id === pid)) {
                        delete newSelectedSpecs[key];
                        delete newSelectedSpecsIds[key];
                    }
                });
                newSelectedSpecs[pid] = spec.attrName;
                newSelectedSpecsIds[pid] = spec.id;
            }

            // 使用新对象触发响应式更新
            this.selectedSpecs = { ...newSelectedSpecs };
            this.selectedSpecsIds = { ...newSelectedSpecsIds };
            console.log(this.selectedSpecs, this.selectedSpecsIds,'selectedSpecs');

            // this.updateStockStatus();

            this.selectedSukIds=Object.values(this.selectedSpecsIds)
            this.selectedSukValues=Object.values(this.selectedSpecs)
            this.selectedSukPids=Object.keys(this.selectedSpecs)
            // this.selectedSuk = Object.values(this.selectedSpecs).join(',');
            // 替换原来的selectedSuk生成方式
            this.selectedSuk = this.getOrderedSuk();
            console.log(this.selectedSuk,'selectedSuk')
            // const matchingAttrValue = this.ebStoreProductAttrValue.find(item => item.suk === this.selectedSuk);

            const matchingAttrValue = this.ebStoreProductAttrValue.find(item => {
                // 统一排序后进行匹配
                const sortedSuk = item.suk.split(',').sort().join(',');
                const selectedSorted = this.selectedSuk.split(',').sort().join(',');
                return sortedSuk === selectedSorted;
            });
            console.log(matchingAttrValue,'matchingAttrValue');
            this.selectedAttrValue = matchingAttrValue
            if (matchingAttrValue) {
                this.price = matchingAttrValue.price;
                this.score = matchingAttrValue.integral;
                this.productAttrValueId = matchingAttrValue.id
                this.imageUrl = matchingAttrValue.image
            }else {
                // 如果没有匹配的规格组合，重置价格和积分
                this.price = this.price
                this.score = this.score
                this.productAttrValueId = this.productAttrValueId
                this.imageUrl = this.imageUrl
            }
        },
        // updateStockStatus() {
        //     // 假设当前选择的是颜色规格，更新尺码规格的状态
        //     if (this.selectedSpecs[121]) { // 假设 121 是颜色规格的 pid
        //         const selectedColor = this.selectedSpecs[121];
        //         this.ebProductAttr.forEach(group => {
        //             if (group.id === 126) { // 假设 126 是尺码规格的 pid
        //                 group.ebProductAttrSecond.forEach(sizeSpec => {
        //                     sizeSpec.disabled = false;
        //                     sizeSpec.outOfStock = false;
        //                     const combinedSuk = `${selectedColor},${sizeSpec.attrName}`;
        //                     const matchingAttrValue = this.ebStoreProductAttrValue.find(item => item.suk === combinedSuk);
        //                     if (matchingAttrValue && matchingAttrValue.stock === 0) {
        //                         sizeSpec.disabled = true;
        //                         sizeSpec.outOfStock = true;
        //                     }
        //                 });
        //             }
        //         });
        //     }
        // },
        // 原有的  只进行了库存的判断
        // updateStockStatus() {
        //     // 重新计算库存状态
        //     this.ebProductAttr.forEach(group => {
        //         group.ebProductAttrSecond.forEach(spec => {
        //             spec.disabled = false;
        //             spec.outOfStock = false;
        //             const newSelectedSpecs = {...this.selectedSpecs };
        //             newSelectedSpecs[group.id] = spec.attrName;
        //             const newSuk = Object.values(newSelectedSpecs).join(',');
        //             const matchingAttrValue = this.ebStoreProductAttrValue.find(item => item.suk === newSuk);
        //             if (matchingAttrValue && matchingAttrValue.stock === 0) {
        //                 spec.outOfStock = true;
        //                 spec.disabled = true;
        //             }
        //         });
        //     });
        // },

        updateStockStatus() {
            // 重置所有规格状态
            this.ebProductAttr.forEach(group => {
                group.ebProductAttrSecond.forEach(currentSpec => {
                    // 保留初始禁用状态（新增判断）
                    if (!currentSpec.permanentDisable) {  //非永久禁用的   都设为false
                        currentSpec.disabled = false;
                        currentSpec.outOfStock = false;
                    }
                });
            });
            console.log(this.ebProductAttr, 'this.ebProductAttr', 'updateStockStatus');
            // 优化组合验证逻辑
            const selectedGroups = Object.keys(this.selectedSpecs);
            const selectedSpecs = Object.values(this.selectedSpecs);
            // 仅处理选中规格的关联验证
            Object.keys(this.selectedSpecs).forEach(selectedPid => {
                const selectedValue = this.selectedSpecs[selectedPid];
                console.log(selectedPid, "selectedPid, ", selectedValue, 'selectedValue');
                this.ebProductAttr.forEach(targetGroup => {
                    // 跳过当前选中规格的组 属性  
                    if (targetGroup.id.toString() === selectedPid) return;
                    console.log(targetGroup, "targetGroup", targetGroup.id.toString(), selectedPid);
                    targetGroup.ebProductAttrSecond.forEach(targetSpec => {
                        console.log(targetSpec, "targetSpec");
                        // 跳过已经被初始禁用的规格
                        if (targetSpec.disabled) return;
                        // 生成跨组组合（包含所有已选规格）
                        const combinedSpecs = {
                            ...this.selectedSpecs,
                            [targetGroup.id]: targetSpec.attrName
                        };
                        console.log(combinedSpecs, 'combinedSpecs', targetGroup.id,);

                        // 检查组合有效性
                        // 生成有序规格字符串
                        const sortedKeys = Object.keys(combinedSpecs).sort();
                        console.log(sortedKeys, 'sortedKeys');
                        const selectedValues = Object.values(combinedSpecs).sort().join(',');
                        // const selectedValues = sortedKeys.map(k => combinedSpecs[k]).sort().join(',');
                        console.log(selectedValues, 'selectedValues');

                        // debugger
                        const matchingAttrValue = this.ebStoreProductAttrValue.find(item => {
                            const itemSpecs = item.suk.split(',').sort().join(',');
                            return itemSpecs === selectedValues;
                        });
                        // 调试输出
                        console.log('验证组合:', {
                            当前选择: this.selectedSpecs,
                            目标规格: targetSpec.attrName,
                            生成组合: combinedSpecs,
                            匹配库存项: matchingAttrValue
                        });
                        if (matchingAttrValue) {
                            const hasStock = matchingAttrValue.stock > 0;
                            targetSpec.disabled = !hasStock;
                            targetSpec.outOfStock = !hasStock;
                        } else {
                            targetSpec.disabled = true;
                        }
                    });
                });
            });
            this.$forceUpdate();
        },
        isSpecSelected(specIds) {
            return specIds.every(spec => {
                const parts = spec.split(' ')[0].split('*');
                console.log(parts,'parts---')
                const id = parts.length === 2? parts[0].trim() : spec;
                console.log(id,'id----')
                return this.selectedSuk.includes(id);
            });
        },
        isSelected(pid,single) {
            return this.selectedSpecs[pid] === single.attrName;
        },
        isOutOfStock() {
            const selectedSuk = Object.values(this.selectedSpecs).join(',');
            return this.ebStoreProductAttrValue.some(item => item.suk === selectedSuk && item.stock === 0);
        },

        // 修改数量
        handleStepperChange(e) {
            this.buyNum = e.detail;
        },
        // 关闭弹窗
        closePopup() {
            this.$emit('closeSpecsPopup')
        },

        // 加入购物车
        addToCart() {
            // this.$emit('addToCart')
            if (this.ebProductAttr.length > 0) {
                if (this.selectedSukIds.length === 0) {
                    Toast('请选择规格')
                } else {
                    if (this.selectedSukIds.length === this.ebProductAttr.length) {
                        const params = {
                            cartId: undefined,
                            cartNum: this.buyNum,
                            cartType: "NORMAL",
                            // combinationId: 0,
                            productAttrValueId: this.productAttrValueId,
                            productId: this.productId,
                            selected: true
                        }
                        addToShoppingCartApi(params).then((res) => {
                            if (res.code === 200) {
                                Toast('加入购物车成功')
                                this.$emit('closeSpecsPopup')
                            }
                        })

                    } else if (this.selectedSukIds.length < this.ebProductAttr.length) {
                        // const idObject = {};
                        // this.curObj.forEach((obj) => {
                        //     idObject[obj.pid] = true;
                        // });
                        // console.log(idObject, 'idObject')
                        // const missingItems = this.specsList.filter((obj) => !idObject[obj.id]).map((obj) => obj.attrName);
                        const missingItems = this.findMissingElements(this.selectedSukPids, this.ebProductAttr)

                        console.log(missingItems, 'missingItems')

                        Toast('请选择' + missingItems)
                    } else {

                    }
                }
            }

        },

        // 确定按钮  修改规格
        onClickBuy() {
            console.log(this.selectedSukPids,this.selectedSukIds,'选中规定的 属性id + 选中的规格id')
            if (this.ebProductAttr.length > 0) {
                if (this.selectedSukIds.length === 0) {
                    Toast('请选择规格')
                } else {
                    if (this.selectedSukIds.length === this.ebProductAttr.length) {
                        console.log(this.selectedAttrValue, 'this.selectedAttrValue')

                        const pa = {
                            cartId: this.cartId,
                            productAttrValueId: this.selectedAttrValue.id,
                            buyNum: this.buyNum
                        }
                        multiSpecAndNumModifyApi(pa).then((res) => {
                            console.log(res, 'res')
                            if (res.code === 200) {
                                Toast('规格已修改')
                                this.closePopup()
                                this.$emit('changeSpecsPopup')
                            }
                        })

                    } else if (this.selectedSukIds.length < this.ebProductAttr.length) {
                        const missingItems = this.findMissingElements(this.selectedSukPids, this.ebProductAttr)

                        console.log(missingItems, 'missingItems')

                        Toast('请选择' + missingItems)
                    } else {

                    }
                }
            }else{
                this.selectedAttrValue =  this.ebStoreProductAttrValue.length>0 ? this.ebStoreProductAttrValue[0] :null
                const apiParams = {
                    cartId: this.cartId,
                    productAttrValueId: this.selectedAttrValue.id,
                    buyNum: this.buyNum
                }
                console.log(apiParams,'apiParams')
                multiSpecAndNumModifyApi(apiParams).then((res) => {
                    console.log(res, 'res')
                    if (res.code === 200) {
                        Toast('规格已修改')
                        this.closePopup()
                        this.$emit('changeSpecsPopup')
                    }
                })

            }

        },
        // 筛选出没有选中的属性名称
        findMissingElements(a, b) {
            let missingAttrNames = [];
            for (let element of b) {
                let found = false;
                for (let item of a) {
                    if (Number(item) === Number(element.id)) {
                        found = true;
                        break;
                    }
                }
                if (!found) {
                    missingAttrNames.push(element.attrName);
                }
            }
            return missingAttrNames;
        },
        // 
        onClickGroupBuy() {
            const params = {}
            uni.navigateTo({
                url:
                    '/pages/shoppingCart/settlement?params=' +
                    encodeURIComponent(JSON.stringify(params))
            })
        },
        // 加入购物车
        // addToShoppingCartMethod() {

        //     return new Promise((resolve, reject) => {
        //         addToShoppingCartApi().then((res) => {
        //             console.log(res, 'res')
        //             if (res.code === 200) {

        //                 resolve(res)
        //             } else {
        //                 reject(res)
        //             }
        //         })
        //     })
        // }
    }
}
</script>
<style lang="scss" scoped>
// @import '@/styles/variables.scss';

// 最外层
.content {
    display: flex;
    flex-direction: column;
    box-sizing: border-box;
    overflow-y: auto;
    z-index: -2;
    scrollbar-width: none;
    /* 针对Firefox */
}

// 滚动
.scroll-content {
    flex: 1;
    height: 1px;
}

// 提示框
.popup-content {
    display: flex;
    flex-direction: column;
    box-sizing: border-box;
    padding: 24px;
    border-radius: 16px;
    overflow: hidden;
    // height:100vh;
    height: 100%;

    .popup-main {
        display: flex;
        flex-direction: column;
        box-sizing: border-box;
        height: calc(100% - 30px);
    }

    .goodsDetail {
        display: flex;
        // align-items: center;
        padding-bottom: 8px;
        // width: 100%;
        width: calc(100% - 30px);
    }

    .goodsPic {
        // width: 25%;
        width: 180rpx;
        height: 180rpx;
        // 让图片居中
        display: flex;
        justify-content: center;
        align-items: center;
        overflow: hidden;  // 新增：隐藏超出部分
        // position: relative;  // 新增

        .img {
            // width: 100%;
            // height: auto;
            width: 100%;
            height: 100%;
            object-fit: cover;  // 关键属性：裁剪而非压缩
            // object-fit: contain; /* 改为contain保持比例 */
            // position: absolute;  // 新增

        }
    }

    .goodsText {
        padding-left: 34rpx;
        position: relative;
        width: calc(100% - 214rpx);
        display: flex;
        flex-direction: column;
        justify-content: center;

        // 价格
        .goods_price {
            position: absolute;
            top: 5%;
            display: flex;
            align-items: center;
            text-align: left;

            .goods_price_num {
                font-weight: bolder;
                font-size: 20px;
                text-align: left;
                color: #111111;
                line-height: 20px;
            }

            .goods_price_text {
                font-size: 12px;
                text-align: left;
                color: #111111;
                line-height: 12px;
            }
        }

        .goods_T {
            position: absolute;
            // bottom: 10%;
            top: 45%;
            font-size: 12px;
            text-align: left;
            color: #888888;
            // line-height: 12px;
            // margin-top: 18px;
        }

    }

    // 选规格   口味 重量 数量
    .specs-box {
        margin-top: 28px;

        .specs-box-title {
            // font-weight: 400;
            font-size: 14px;
            text-align: left;
            color: #666666;
            line-height: 14px;

            .specs-box-title-span {
                // font-weight: 400;
                font-size: 14px;
                text-align: left;
                color: #111111;
                line-height: 14px;
            }
        }

        .specs-box-select {
            margin-top: 15px;
        }

        .popup-sort {
            display: flex;
            justify-content: flex-start;
            align-items: center;
            flex-wrap: wrap;
        }

        .popup-item {
            margin-right: 12px;
            margin-bottom: 12px;
            height: 28px;
            line-height: 28px;
            padding-left: 24px;
            padding-right: 24px;
        }

        // 有库存
        .inStock {
            border: 1px solid #D6D6D6;
            font-size: 13px;
            text-align: center;
            color: #333333;

            &.active {
                border: 1px solid #111111;
                color: #111111;
                font-size: 14px;
            }
        }

        // 某一规格没有了
        .soldOut {
            font-size: 13px;
            color: #999999;
            border: 1px solid #999999;
        }
    }
}

.number {
    padding-bottom: 20px;
}

.l20 {
    margin-left: 20px;
}

.r13 {
    margin-right: 13px;
}

.r8 {
    margin-right: 8px;
}

.my-goods-action {
    .van-goods-action-button {
        color: green;
        background-color: orange;
    }
}

::v-deep .my-goods-action .van-goods-action, .van-goods-action--safe{
    border-top: 1px solid #f9f9f9 !important;
}

::v-deep .minus-class,
.van-stepper__minus,
.van-stepper__minus--disabled {
    border-radius: 50px !important;
}

// stepper    步进器
// 左边的数字
::v-deep .minus-class,
.van-stepper__minus {
    border-radius: 50px !important;
    background-color: #ffffff !important;
    border: 1px solid #111111 !important;
    width: 23px !important;
    height: 23px !important;
    line-height: 23px !important;
}

// 及不能被点击的最小数字
::v-deep .van-stepper__minus--disabled {
    border-radius: 50px !important;
    background-color: #ffffff !important;
    border: 1px solid #999999 !important;
    width: 23px !important;
    height: 23px !important;
    line-height: 23px !important;
}

// 中间的数字
::v-deep .input-class,
.van-stepper__input {
    border-radius: 50px !important;
    background-color: transparent !important;
}

// 右侧最大的数字
::v-deep .plus-class,
.van-stepper__plus {
    border-radius: 50px !important;
    background-color: #ffffff !important;
    border: 1px solid #111111 !important;
    width: 23px !important;
    height: 23px !important;
    line-height: 23px !important;
}

// 以及不能被点击状态
::v-deep .van-stepper__plus--disabled {
    border-radius: 50px !important;
    border: 1px solid #999999 !important;
    background-color: #ffffff !important;
    width: 23px !important;
    height: 23px !important;
    line-height: 23px !important;
}
::v-deep .van-button--primary {
  width: 100%;
  height: 86rpx;
  border-radius: 50rpx;
  background: #ff6203;
  margin-top: 32rpx;
  font-size: 28rpx;
}

.normal {
    display: inline-block;
    width: 140px;
    height: 40px;
    line-height: 40px;
    margin: 10px;
    border: 1px solid #ccc;
    text-align: center;
}

.cur_border {
    border-color: #111111 !important;
    color: #111111;
    /* color: #000; */
}

.dis_border {
    position: relative;
    border-color: #999999 !important;
    font-size: 26rpx;
    color: #999999 !important;
    pointer-events: none;
}
.dis_border {
    position: relative;
    border-color: #999999 !important;
    font-size: 26rpx;
    color: #999999 !important;
    pointer-events: none;
    opacity: 0.6;
}

.out-of-stock {
    position: relative;
    border-color: #999999 !important;
    font-size: 26rpx;
    color: #999999 !important;
    pointer-events: none;
    opacity: 0.6;
}

.out-of-stock::before {
    content: "缺货";
    position: absolute;
    width: 40px;
    height: 20px;
    background: #fff;
    top: -13px; //-20px
    right: -10px;
    font-size: 10px;
}

// .dis_border::before {
//     content: "缺货";
//     position: absolute;
//     width: 40px;
//     height: 20px;
//     background: #fff;
//     top: -20px;
//     right: -10px;
//     font-size: 10px;
// }

.out-of-stock-tip {
    color: red;
    margin-top: 20px;
}
.out-of-stock-tag {
    color: red;
    margin-left: 5px;
}
.bottom{
    padding-left: 0;
    padding-right: 0;
}

</style>
